#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_uart.h"
#include "iot_errno.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <time.h>
#include "cJSON.h"
#include "cmsis_os2.h"
#include "socket.h"

#include "esp_netif.h"
#include "esp_log.h"
#include "lwip/err.h"
#include "lwip/netif.h"
#include "lwip/ip4.h"
#include "lwip/inet.h"
#include "sys/socket.h"
#include "string.h"
#include "stdlib.h"
#include "unistd.h"

#include "esp_log.h"
#include "tcpip_adapter.h"
#include <netinet/in.h> // 包含 sockaddr_in 相关定义
#include <arpa/inet.h>  // 包含 inet_ntoa 等函数
#include <stdio.h>      // 包含 printf 等标准输入输出函数

#define TASK_STACK_SIZE 1024 * 8 // 任务栈大小
#define TASK_PRIO 20
#define IOT_UART_IDX 1

// #define CHESS_NUM 9
#define PORT 8080
#define BUFFER_SIZE 128
// #define BOARD_SIZE 9
#define MATRIX_SIZE 3
#define MATRIX_SQUARE MATRIX_SIZE*MATRIX_SIZE
#define NINE 9
#define MAX_VALUE MATRIX_SIZE + '0'
// #define BUFF_SIZE               100
int chessMatrix[MATRIX_SQUARE] = {0};
int receivedAnsver[MATRIX_SQUARE] = {0};

// 问题下发完成标志
int gQuestionWriteDone = 0;
// 答题结果正确标志
int gQuestionResultDone = 0;

// 存放L2下发的JSON数据包的结构体
typedef struct _question_data
{
    uint8_t questionNum;          // 题号
    char question[MATRIX_SQUARE + 1]; // 题目
    char answer[MATRIX_SQUARE + 1];   // 正确答案
} question_data;

question_data original_questionData;

static osThreadId_t g_tid = NULL;

// 定义一个 9x9 的棋盘
// int chessBoard[MATRIX_SIZE][MATRIX_SIZE] = {0};
pthread_mutex_t board_mutex = PTHREAD_MUTEX_INITIALIZER; // 保护棋盘的互斥锁
// 询问答题结果命令
static const unsigned char *getResultCmd = "AT+C=?\r\n";
// const char *jsonStr2 = "{\"problem\":2,\"question\":\"300120200\",\"answer\":\"312123231\"}";
// const char *jsonStr1 = "{\"problem\":1,\"question\":\"100200312\",\"answer\":\"123231312\"}";

void IotUartInit(void)
{
    int32_t ret;
    IotUartAttribute uart_attr = {
        .baudRate = 115200,
        .dataBits = 8,
        .stopBits = 1,
        .parity = 0,
    };
    ret = IoTUartDeinit(IOT_UART_IDX);
    //初始化UART driver
    ret = IoTUartInit(IOT_UART_IDX,&uart_attr);
    if (ret != IOT_SUCCESS)
    {
        printf("\nInit Uart Falied Error No : %d\n", ret);
        //return; //不可以直接返回
    }
    printf("\nIotUartInit Start!!!\n");
}

// 读取答题结果任务
void AT_C_getAnswer(void)
{
    int32_t ret;
    uint8_t uartR_buff[BUFFER_SIZE] = {0};
    uint8_t *uartR_buff_p = uartR_buff;
    uint8_t *pPos = NULL;

    // ret = IoTUartSetFlowCtrl(IOT_UART_IDX, IOT_FLOW_CTRL_NONE);
    printf("AT_C_getAnswer Test Start!!!\n");
     
    // 发送询问命令 AT+C=？/r/n  接收AT+C=RESULT/r/n
    ret = IoTUartWrite(IOT_UART_IDX, (unsigned char *)getResultCmd, strlen(getResultCmd));
    if (ret != IOT_SUCCESS)
    {
        printf("Send Request Cmd No : %d, %s\n", ret, getResultCmd);
        //return;
    }
    osDelay(1000);

    // 读取返回结果AT+C=RESULT/r/n
    ret = IoTUartRead(IOT_UART_IDX, uartR_buff_p, BUFFER_SIZE);
    if (ret < 0)
    {
        printf("UartRead: read data failed, ret %d\n", ret);
    }
    else if (ret > 0)
    {
        printf("read : %s\r\n", uartR_buff_p);
        uartR_buff_p[ret] = '\0';

        // ret = IoTUartWrite(IOT_UART_IDX,(uint8_t *)uart_buff_p,strlen(uart_buff_p));

        // 匹配串口收到的数据内容
        // AT+C=RESULT/r/n/r/n  成功
        pPos = strstr(uartR_buff_p, "AT+C=");
        if (pPos == NULL)
        {
            // 没收到“AT+C=/r/n”返回值打印日志
            printf("Not receive  AT+C=RESULT !");
        }else
        {
            printf("AT+C= Substring found at position: %ld\n", pPos - uartR_buff_p); // 输出字串位置

            // 1.获取uart_buff的实际大小，与MATRIX_SQUARE进行对比，相等再进行下一步
            if (strlen(uartR_buff) - strlen("AT+C=") >= MATRIX_SQUARE)
            {
                printf("\nReceived result len %d\r\n", strlen(uartR_buff) - strlen("AT+C="));
                
                // 2.读取RESULT结果放到receivedAnsver数组中
                pPos = pPos + strlen("AT+C=");//此处位置有疑问？
                for (int i = 0; i < MATRIX_SQUARE; i++)
                {
                    receivedAnsver[i] = *pPos - '0';
                    pPos++;
                    // receivedAnsver[i] = uartR_buff[i]- '0';
                }

                //串口打印收到的答题结果
                printf("receivedAnsver: ");
                for (int i = 0; i < MATRIX_SQUARE; i++)
                {
                    printf("%d", receivedAnsver[i]);
                }
                printf("\n");

                //3.分析收到的答题结果
                ret = analyzeResult();
                if (ret == IOT_SUCCESS)
                {
                    printf("uart analyzeResult() success\r\n");
                }
                else
                {
                    printf("uart analyzeResult() fail\r\n");
                }
            
            }

        }
        
    }
    memset(uartR_buff_p, 0, BUFFER_SIZE);
    osDelay(1000);
    //}
    //ret = IoTUartDeinit(IOT_UART_IDX);
    // if (ret == IOT_SUCCESS)
    // {
    //     printf("uart deinit success\r\n");
    // }
    // else
    // {
    //     printf("uart deinit fail\r\n");
    // }
    // 清除标志
    //gQuestionWriteDone = 0;

    //osThreadExit();
}

// 判断收到的答案是否正确
int analyzeResult(void)
{
    printf("analyzeResult Test Start!!!\n");
    int ret = 1;
    char uartW_buffer[BUFFER_SIZE]; // 需定义足够大的缓冲区
    uint8_t uartR_buff[BUFFER_SIZE] = {0};
    uint8_t *uartR_buff_p = uartR_buff;

    if (isBoardFullyFilled())//查看是否答题完成
    {
        printf("Board is fully filled. Verifying...\n");
        if (verifyBoardWithAnswer())
        {
            //gQuestionResultDone = 1;
            // 答题正确下发AT+D=1/r/n  回传AT+D=OK/r/n  成功
            printf("Board is correctly filled according to the answer.\n");

            sprintf(uartW_buffer, "AT+D=1\r\n");
            ret = IoTUartWrite(IOT_UART_IDX, (unsigned char *)uartW_buffer, strlen(uartW_buffer));
            osDelay(5000);

            //5秒钟后正常显示棋盘内容
            sprintf(uartW_buffer, "AT+D=3\r\n");
            ret = IoTUartWrite(IOT_UART_IDX, (unsigned char *)uartW_buffer, strlen(uartW_buffer));
        }
        else
        {
            // 答案错误下发AT+D=2/r/n  回传AT+D=ERROR/r/n  失败
            printf("Board is filled, but does not match the answer.\n");
            gQuestionResultDone = 0;
            sprintf(uartW_buffer, "AT+D=2\r\n");
            ret = IoTUartWrite(IOT_UART_IDX, (unsigned char *)uartW_buffer, strlen(uartW_buffer));

            //5秒钟后正常显示棋盘内容
            sprintf(uartW_buffer, "AT+D=3\r\n");
            ret = IoTUartWrite(IOT_UART_IDX, (unsigned char *)uartW_buffer, strlen(uartW_buffer));
        }
        
        if (ret != IOT_SUCCESS)
        {
            printf("AnalyzeResult receive No : %d\n", ret);
            return ret;
        }

        osDelay(1000);
        // 读取返回结果
        ret = IoTUartRead(IOT_UART_IDX, uartR_buff_p, BUFFER_SIZE);
        if (ret < 0)
        {
            printf("UartRead: read data failed, ret %d\n", ret);
        }
        else if (ret > 0)
        {

            printf("read : %s\r\n", uartR_buff_p);
            uartR_buff_p[ret] = '\0';

            // 匹配串口收到的数据内容
            // 回传AT+D=OK/r/n  成功

            if (strstr(uartR_buff, "AT+D=OK/r/n"))
            {
                printf("receive AT+D=OK !\n"); // 输出：子串位置
                ret = IOT_SUCCESS;
            }
        }
    }
    return ret;
}

// AT_W函数
void AT_W_WriteCommand(int pos, int num)
{
    //printf("entry: AT_W_WriteCommand\n");
    int status = 1, ret;
    char uartW_Buffer[BUFFER_SIZE]; // 需定义足够大的缓冲区
    char *pPos = NULL;

    uint8_t uartR_buff[BUFFER_SIZE] = {0};
    uint8_t *uartR_buff_p = uartR_buff;

    if (num == 0) // 数值为0表示不锁定
    {
        status = 0;
    }

    // 写入棋子内容 单片机设置是从位置1开始，此处需要pos+1
    sprintf(uartW_Buffer, "AT+W=%d %d %d\r\n", pos+1, num, status);
    ret = IoTUartWrite(IOT_UART_IDX, (unsigned char *)uartW_Buffer, strlen(uartW_Buffer));
    // if (ret != IOT_SUCCESS)
    // {
    //     printf("Uart AT+W No : %d, %s\n", ret, uartW_Buffer);
    //     //return ret;//串口函数不可返回
    // }

    // 读取返回结果
    ret = IoTUartRead(IOT_UART_IDX, uartR_buff_p, BUFFER_SIZE);
    // osDelay(1000);
    if (ret < 0)
    {
        printf("UartRead: AT+W read data failed, ret %d\n", ret);
    }
    else if (ret > 0)
    {
        printf("read : %s\r\n", uartR_buff_p);
        uartR_buff_p[ret] = '\0';

        // // 匹配串口收到的数据内容
        // // AT+W=OK/r/n  成功
        // pPos = strstr(uartR_buff, "AT+W=OK");
        // if (pPos != NULL)
        // {
        //     printf("receive AT+W=OK\n");
        // }
        // else
        // {
        //     // 没收到“AT+W=OK\r\n”返回值,如何处理还没定
        //     // 其中一个想法：下发False显示：AT+D=2/r/n
        //     printf("Not receive AT+W=OK\n");        
        //     //写函数出问题后如何处理，不再继续下发数据，此处代码需要完善
        // }
    }

    // //AT+W测试
    // sprintf(uartW_Buffer, "AT+W=1 2 1\r\n"); 
    // for (int i = 0; i<5; i++)
    // {
    //     ret = IoTUartWrite(IOT_UART_IDX, (unsigned char *)uartW_Buffer, strlen(uartW_Buffer));
    //     if (ret != IOT_SUCCESS)
    //     {
    //         printf("\n Uart AT-W No : %d\n", ret);
    //         //return ret; 
    //     }

    //     ret = IoTUartRead(IOT_UART_IDX, uartR_buff_p, BUFFER_SIZE);
    //     osDelay(5000);
    //     if (ret < 0)
    //     {
    //         printf("UartRead: read data failed, ret %d\n", ret);
    //     }
    //     else if (ret > 0)
    //     {
    //         printf("read : %s\r\n", uartR_buff_p);
    //     }
    // }

    // //AT+R测试
    // sprintf(uartW_Buffer, "AT+R=1\r\n"); 
    // for (int i = 0; i<5; i++)
    // {
    //     ret = IoTUartWrite(IOT_UART_IDX, (unsigned char *)uartW_Buffer, strlen(uartW_Buffer));
    //     if (ret != IOT_SUCCESS)
    //     {
    //         printf("\n Uart AT-R No : %d\n", ret);
    //         //return ret; //不需要返回
    //     }

    //     ret = IoTUartRead(IOT_UART_IDX, uartR_buff_p, BUFFER_SIZE);
    //     osDelay(5000);
    //     if (ret < 0)
    //     {
    //         printf("UartRead: read data failed, ret %d\n", ret);
    //     }
    //     else if (ret > 0)
    //     {
    //         printf("read : %s\r\n", uartR_buff_p);
    //     }
    // }

    // //AT+C测试
    // sprintf(uartW_Buffer, "AT+C=?\r\n"); 
    // for (int i = 0; i<5; i++)
    // {
    //     ret = IoTUartWrite(IOT_UART_IDX, (unsigned char *)uartW_Buffer, strlen(uartW_Buffer));
    //     if (ret != IOT_SUCCESS)
    //     {
    //         printf("\n Uart AT-C No : %d\n", ret);
    //         //return ret; //不需要返回
    //     }

    //     ret = IoTUartRead(IOT_UART_IDX, uartR_buff_p, BUFFER_SIZE);
    //     osDelay(5000);
    //     if (ret < 0)
    //     {
    //         printf("UartRead: read data failed, ret %d\n", ret);
    //     }
    //     else if (ret > 0)
    //     {
    //         printf("read : %s\r\n", uartR_buff_p);
    //     }
    // }

    // //AT+D测试
    // sprintf(uartW_Buffer, "AT+D=1\r\n"); 
    // for (int i = 0; i<5; i++)
    // {
    //     ret = IoTUartWrite(IOT_UART_IDX, (unsigned char *)uartW_Buffer, strlen(uartW_Buffer));
    //     if (ret != IOT_SUCCESS)
    //     {
    //         printf("\n Uart AT-D No : %d\n", ret);
    //         //return ret; //不需要返回
    //     }

    //     ret = IoTUartRead(IOT_UART_IDX, uartR_buff_p, BUFFER_SIZE);
    //     osDelay(5000);
    //     if (ret < 0)
    //     {
    //         printf("UartRead: read data failed, ret %d\n", ret);
    //     }
    //     else if (ret > 0)
    //     {
    //         printf("read : %s\r\n", uartR_buff_p);
    //     }
    // }

    // sprintf(uartW_Buffer, "AT+D=2\r\n"); 
    // for (int i = 0; i<5; i++)
    // {
    //     ret = IoTUartWrite(IOT_UART_IDX, (unsigned char *)uartW_Buffer, strlen(uartW_Buffer));
    //     if (ret != IOT_SUCCESS)
    //     {
    //         printf("\n Uart AT-D No : %d\n", ret);
    //         //return ret; //不需要返回
    //     }

    //     ret = IoTUartRead(IOT_UART_IDX, uartR_buff_p, BUFFER_SIZE);
    //     osDelay(5000);
    //     if (ret < 0)
    //     {
    //         printf("UartRead: read data failed, ret %d\n", ret);
    //     }
    //     else if (ret > 0)
    //     {
    //         printf("read : %s\r\n", uartR_buff_p);
    //     }
    // }

    // sprintf(uartW_Buffer, "AT+D=3\r\n"); 
    // for (int i = 0; i<5; i++)
    // {
    //     ret = IoTUartWrite(IOT_UART_IDX, (unsigned char *)uartW_Buffer, strlen(uartW_Buffer));
    //     if (ret != IOT_SUCCESS)
    //     {
    //         printf("\n Uart AT-D No : %d\n", ret);
    //         //return ret; //不需要返回
    //     }

    //     ret = IoTUartRead(IOT_UART_IDX, uartR_buff_p, BUFFER_SIZE);
    //     osDelay(5000);
    //     if (ret < 0)
    //     {
    //         printf("UartRead: read data failed, ret %d\n", ret);
    //     }
    //     else if (ret > 0)
    //     {
    //         printf("read : %s\r\n", uartR_buff_p);
    //     }
    // }

    //无返回值

    //return ret;
}

// 函数：检查棋盘是否全部填充，即答题是否完成
int isBoardFullyFilled(void)
{
    // pthread_mutex_lock(&board_mutex);
    for (int i = 0; i < MATRIX_SQUARE; i++)
    {
        if (receivedAnsver[i] == 0)
        {
            // pthread_mutex_unlock(&board_mutex);
            printf("isBoardFullyFilled failed\n");
            return 0; // 未全部填充
        }
    }
    // pthread_mutex_unlock(&board_mutex);
    return 1; // 全部填充
}

// 函数：验证棋盘状态是否满足 answer 的要求
// receivedAnsver 收到的结果
// original_questionData.answer 存放的正确答案
int verifyBoardWithAnswer(void)
{
    // pthread_mutex_lock(&board_mutex);
    for (int i = 0; i < MATRIX_SQUARE; i++)
    {
        if (receivedAnsver[i] != original_questionData.answer[i] - '0')
        {
            // pthread_mutex_unlock(&board_mutex);
            printf("verifyBoardWithAnswer failed\n");
            return 0; // 不满足要求
        }
    }
    // pthread_mutex_unlock(&board_mutex);
    return 1; // 满足要求
}

// 函数：使用 question 数据填充棋盘
int fillBoardWithQuestion(const char *question)
{
    printf("entry: fillBoardWithQuestion\n");
    int ret;
    if (strlen(question) != MATRIX_SQUARE)
    {

        printf("entry: strlen(question):%d; MATRIX_SQUARE:%d\n",strlen(question),MATRIX_SQUARE);
        return -1; // question 长度不正确
    }
   
    for (int i = 0; i < MATRIX_SQUARE; i++)
    {
        chessMatrix[i] = question[i] - '0'; // 将字符转换为数字
        printf("\n entry: chessMatrix[%d]:%d\n",i,chessMatrix[i]);
        AT_W_WriteCommand(i, chessMatrix[i]);
        //写函数出问题后返回，不再继续下发数据，此处代码需要完善
    }

    // 对比原始题目和chessMatrix中的内容是否一致，一致表明题目已下发完毕
    // chessMatrix;//棋盘数组中存放的是数字
    // original_questionData.question //json下发的是字符串
    for (int i = 0; i < MATRIX_SQUARE; i++)
    {
        if (chessMatrix[i] != original_questionData.question[i] - '0') // 将字符转换为数字
        {
            printf("question is not finish!.\n");
            return -1;
        }
    }

    if (ret == IOT_SUCCESS)
    {
        printf("placePiece is successful!\n");
    }
    else
    {
        printf("placePiece is failed!\n");
    }

    return IOT_SUCCESS; // 成功
}

// 函数：解析 JSON 数据为 C 字符串
char *parse_json_to_c_string(const char *json_data)
{
    printf("entry: parse_json_to_c_string\n");
    cJSON *json = cJSON_Parse(json_data);
    if (json == NULL)
    {
        const char *error_ptr = cJSON_GetErrorPtr();
        if (error_ptr != NULL)
        {
            fprintf(stderr, "Error before: %s\n", error_ptr);
        }
        return strdup("Invalid JSON data");
    }

    cJSON *problem = cJSON_GetObjectItemCaseSensitive(json, "problem");   // 题号
    cJSON *question = cJSON_GetObjectItemCaseSensitive(json, "question"); // 题目
    cJSON *answer = cJSON_GetObjectItemCaseSensitive(json, "answer");     // 正确答案

    if (!cJSON_IsNumber(problem) || !cJSON_IsString(question) || !cJSON_IsString(answer))
    {
        cJSON_Delete(json);
        return strdup("Invalid JSON data: missing or invalid fields");
    }

    if (strlen(question->valuestring) != MATRIX_SQUARE || strlen(answer->valuestring) != MATRIX_SQUARE)
    {
        cJSON_Delete(json);
        printf("question length is %d,answer length is %d,", strlen(question->valuestring), strlen(answer->valuestring));
        return strdup("Invalid JSON data: question or answer length is not MATRIX_SQUARE");
    }

    // 校验 question 和 answer 是否只包含数字
    for (int i = 0; i < MATRIX_SQUARE; i++)
    {
        if (question->valuestring[i] < '0' || question->valuestring[i] > MAX_VALUE ||
            answer->valuestring[i] < '0' || answer->valuestring[i] > MAX_VALUE)
        {
            cJSON_Delete(json);
            return strdup("Invalid JSON data: question or answer contains non-digit characters");
        }
    }

    // 创建一个字符串来存储解析结果
    char *result = (char *)malloc(256 * sizeof(char));
    if (result == NULL)
    {
        cJSON_Delete(json);
        return strdup("Memory allocation failed");
    }

    snprintf(result, 256, "Problem: %d\n Question: %s\n Answer: %s",
             problem->valueint, question->valuestring, answer->valuestring);

    //此处判断新下发得题目与上一次保存得题目是否相同，如果相同则不重新下发
    if ((strcmp(original_questionData.question, question->valuestring) == 0)&&(strcmp(original_questionData.answer, answer->valuestring) == 0))
    {
        printf("\nsame question not need to send again!\n");
        //重复下发如何实现：给个标志位直接return
        gQuestionWriteDone = 1;
        return strdup("Same question Completed!");
    }
    

    // 创建一个实例来存储原题目json解析结果
    original_questionData.questionNum = problem->valueint;
    snprintf(original_questionData.question, 
        sizeof(original_questionData.question),
        "%s", 
        question->valuestring ? question->valuestring : "");

    snprintf(original_questionData.answer, 
        sizeof(original_questionData.answer),
        "%s", 
        answer->valuestring ? answer->valuestring : "");

    //打印原题目实例，测试原题目是否保存正确
    printf("\n original_questionData: \n questionNum = %d,\n question = %s, \n answer = %s\n",original_questionData.questionNum, original_questionData.question, original_questionData.answer);

    cJSON_Delete(json);

    return result;
}

// 获取 IP 地址并赋值到 address.sin_addr.s_addr
void get_ip_and_set_address(esp_netif_t *esp_netif, struct sockaddr_in *address)
{
    esp_netif_ip_info_t ip_info;
    esp_err_t err = esp_netif_get_ip_info(esp_netif, &ip_info);

    if (err != ESP_OK)
    {
        printf("Failed to get IP info, error: %d", err);
        return;
    }

    // 将获取到的 IP 地址赋值到 address.sin_addr.s_addr
    address->sin_family = AF_INET;
    address->sin_port = htons(PORT);
    address->sin_addr.s_addr = ip_info.ip.addr;

    // 打印 address 的值
    printf("address.sin_family: %d", address->sin_family);
    printf("address.sin_port: %d", ntohs(address->sin_port)); // 转换为主机字节序打印
    printf("address.sin_addr.s_addr (raw): 0x%08X", address->sin_addr.s_addr);

    // 打印 IP 地址的字符串形式
    char ip_str[16];
    inet_ntop(AF_INET, &address->sin_addr, ip_str, sizeof(ip_str));
    printf("address.sin_addr.s_addr (string): %s", ip_str);
}
struct sockaddr_in address;
int new_socket;

int get_logs_socket(void)
{
    return new_socket;
}

int SocketTask(void)
{
    int server_fd;

    int addrlen = sizeof(struct sockaddr_in);
    char socketBuffer[BUFFER_SIZE] = {0};
    char *response;

    int32_t ret;

    //串口初始化
    IotUartInit();


    printf("SocketTask %d\n", __LINE__);
    // 创建 socket 文件描述符
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
    {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }
    printf("SocketTask %d\n", __LINE__);
    // 设置 SO_REUSEADDR 选项
    int opt = 1;
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)))
    {
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }
    // 绑定 socket 到指定的 IP 地址和端口
    get_ap_ip_address(&address);
    if (address.sin_addr.s_addr != INADDR_NONE)
    {
        printf("AP IP Address: %s\n", inet_ntoa(address.sin_addr));
    }
    else
    {
        printf("Failed to get AP IP Address\n");
    }

    printf("SocketTask %d\n", __LINE__);

    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0)
    {
        perror("bind failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }
    printf("SocketTask %d\n", __LINE__);
    if (listen(server_fd, 3) < 0)
    {
        perror("listen");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    printf("Server is listening on IP address: INADDR_ANY, port %d...\n", PORT);
    printf("AP IP Address_01: %s\n", inet_ntoa(address.sin_addr));

    if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0)
    {
        perror("accept");
        close(server_fd);
        exit(EXIT_FAILURE);
    }
    printf("AP IP Address: %s\n", inet_ntoa(address.sin_addr));
    printf("Client connected.\n");

    while (true)
    {
        read(new_socket, socketBuffer, BUFFER_SIZE);
        printf("Received data from client socketBuffer: %s\n", socketBuffer);
        gQuestionWriteDone = 0;

        // 安全拷贝（避免缓冲区溢出）
        //测试使用的json字符串 此处应增加一个标志位用于判别是否L2最新下发题目，重复下发题目应该如何处理？
        // strncpy(socketBuffer, jsonStr1, BUFFER_SIZE - 1); //测试使用代码
        socketBuffer[BUFFER_SIZE - 1] = '\0'; // 确保字符串终止
        printf("test: Received data from client socketBuffer: %s\n", socketBuffer);

        //一、解析L2下发的json字符串
        response = parse_json_to_c_string(socketBuffer);

        if (response == NULL)
        {
            response = strdup("Invalid JSON data");
        }

        if(gQuestionWriteDone)
        {
            //已经下发完成直接跳当次循环，相同题目不再下发
            sleep(1);
            continue;
        }
        
        // send(new_socket, response, strlen(response), 0);

        //printf("Sent response to client: %s\n", response);
        //printf("AP IP Address: %s\n", inet_ntoa(address.sin_addr));

        //二、 使用 原始题目中的question 数据填充棋盘
        if (fillBoardWithQuestion(original_questionData.question) == -1)
        {
            strdup("Failed to place pieces on the board");
            printf("Failed to place pieces on the board");
            continue;
        }

        gQuestionWriteDone = 1;   
    }

    free(response);
    close(new_socket);
    close(server_fd);

    printf("Client disconnected.\n");

    ret = IoTUartDeinit(IOT_UART_IDX);
    if(ret == IOT_SUCCESS){
        printf("uart deinit success\r\n");
    }else{
        printf("uart deinit fail\r\n");
    }

    return 0;
}

int GetResultTask(void)
{
    //三、题目下发完毕，进行答案解析
    while (true)
    {
        //等待读取结果标志
        if (!gQuestionWriteDone)
        {
            sleep(1);
            continue;
        }
        AT_C_getAnswer();
        osDelay(1000);
    }
}

void *my_test_thread(void *arg)
{
    while (1)
    {
        printf("my test thread.\n");
        sleep(1); // 稍作延迟
    }
    return NULL;
}

int StartSocketTask(void)
{
    osThreadAttr_t attr;
    attr.name = "SOCKET_TASK";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 8000;
    attr.priority = 25;

    g_tid = osThreadNew((osThreadFunc_t)SocketTask, NULL, &attr);
    if (g_tid == NULL)
    {
        printf("Failed to create socket task!\n");
        return -1;
    }
    printf("Passed to create socket task!\n");

    osThreadAttr_t uartAttr;
    uartAttr.name = "Iot_UART_TASK_NAME";
    uartAttr.attr_bits = 0U;
    uartAttr.cb_mem = NULL;
    uartAttr.cb_size = 0U;
    uartAttr.stack_mem = NULL;
    uartAttr.stack_size = TASK_STACK_SIZE;
    uartAttr.priority = TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)GetResultTask, NULL, &uartAttr) == NULL)
    {
        printf("Failed to create uartAttr thread!\n");
        return -1;
    }

    // 线程测试
    //  pthread_t tid;
    //  pthread_attr_t thattr;
    //  pthread_attr_init(&thattr);
    //  pthread_attr_setdetachstate(&thattr, 1);

    // pthread_create(&tid, &thattr, my_test_thread, NULL);

    return 0;
}

// APP_FEATURE_INIT(StartSocketTask);
// load状态下就开始加载，所以不适用这种方式
